"""Platform-specific instrumentation profiles for domestic supercomputing platforms."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass
class PlatformProfile:
    """Configuration for platform-specific instrumentation."""
    name: str
    timing_library: str
    include_files: List[str]
    init_calls: List[str]
    finalize_calls: List[str]
    start_call_template: str
    stop_call_template: str
    preprocessor_defines: List[str] = None
    link_libraries: List[str] = None
    compiler_flags: List[str] = None
    mpi_support: bool = True
    description: str = ""

    def __post_init__(self):
        if self.preprocessor_defines is None:
            self.preprocessor_defines = []
        if self.link_libraries is None:
            self.link_libraries = []
        if self.compiler_flags is None:
            self.compiler_flags = []


# Platform-specific profiles for domestic supercomputing systems

SUNWAY_PROFILE = PlatformProfile(
    name="sunway",
    timing_library="swTrace",
    include_files=["sw_trace.h"],
    init_calls=[
        "sw_trace_init();",
        "#ifdef SW_MPI\n    sw_trace_mpi_init(MPI_COMM_WORLD);\n#endif"
    ],
    finalize_calls=[
        "#ifdef SW_MPI\n    sw_trace_mpi_finalize();\n#endif",
        "sw_trace_finalize();"
    ],
    start_call_template="sw_trace_start(\"{function_name}\");",
    stop_call_template="sw_trace_stop(\"{function_name}\");",
    preprocessor_defines=["SW_TRACE_ENABLE", "SW_MPI"],
    link_libraries=["sw_trace", "sw_mpi"],
    compiler_flags=["-I/opt/sw/include", "-L/opt/sw/lib"],
    mpi_support=True,
    description="Sunway TaihuLight supercomputer tracing profile"
)

TIANHE_PROFILE = PlatformProfile(
    name="tianhe",
    timing_library="Htrace",
    include_files=["htrace.h"],
    init_calls=[
        "htrace_initialize();",
        "#ifdef HTRACE_MPI\n    htrace_mpi_init();\n#endif"
    ],
    finalize_calls=[
        "#ifdef HTRACE_MPI\n    htrace_mpi_finalize();\n#endif",
        "htrace_finalize();"
    ],
    start_call_template="htrace_region_begin(\"{function_name}\");",
    stop_call_template="htrace_region_end(\"{function_name}\");",
    preprocessor_defines=["HTRACE_ENABLE", "HTRACE_MPI"],
    link_libraries=["htrace", "hmpi"],
    compiler_flags=["-I/opt/tianhe/include", "-L/opt/tianhe/lib"],
    mpi_support=True,
    description="Tianhe-2 supercomputer tracing profile"
)

SUGON_PROFILE = PlatformProfile(
    name="sugon",
    timing_library="PAPI-SW",
    include_files=["papi.h", "papi_sw.h"],
    init_calls=[
        "PAPI_library_init(PAPI_VER_CURRENT);",
        "#ifdef PAPI_MPI\n    PAPI_mpi_init();\n#endif"
    ],
    finalize_calls=[
        "#ifdef PAPI_MPI\n    PAPI_mpi_finalize();\n#endif",
        "PAPI_shutdown();"
    ],
    start_call_template="PAPI_sw_start(\"{function_name}\");",
    stop_call_template="PAPI_sw_stop(\"{function_name}\");",
    preprocessor_defines=["PAPI_SW_ENABLE", "PAPI_MPI"],
    link_libraries=["papi", "papi_sw"],
    compiler_flags=["-I/opt/sugon/include", "-L/opt/sugon/lib"],
    mpi_support=True,
    description="Sugon supercomputer PAPI-SW profiling profile"
)

# Generic GPTL profile (for comparison)
GPTL_PROFILE = PlatformProfile(
    name="gptl",
    timing_library="GPTL",
    include_files=["gptl.h"],
    init_calls=["GPTLinitialize();"],
    finalize_calls=["GPTLfinalize();"],
    start_call_template="GPTLstart(\"{function_name}\");",
    stop_call_template="GPTLstop(\"{function_name}\");",
    preprocessor_defines=["GPTL_ENABLE"],
    link_libraries=["gptl"],
    compiler_flags=[],
    mpi_support=True,
    description="Generic GPTL timing library profile"
)


class PlatformRegistry:
    """Registry of platform-specific profiles."""

    def __init__(self):
        self.profiles: Dict[str, PlatformProfile] = {
            "sunway": SUNWAY_PROFILE,
            "tianhe": TIANHE_PROFILE,
            "sugon": SUGON_PROFILE,
            "gptl": GPTL_PROFILE,
        }

    def get_profile(self, name: str) -> Optional[PlatformProfile]:
        """Get a platform profile by name."""
        return self.profiles.get(name.lower())

    def register_profile(self, profile: PlatformProfile):
        """Register a custom platform profile."""
        self.profiles[profile.name.lower()] = profile

    def list_profiles(self) -> List[str]:
        """List all available platform profile names."""
        return list(self.profiles.keys())

    def get_profile_info(self, name: str) -> str:
        """Get detailed information about a platform profile."""
        profile = self.get_profile(name)
        if not profile:
            return f"Profile '{name}' not found"

        info = [
            f"Platform Profile: {profile.name}",
            f"Description: {profile.description}",
            f"Timing Library: {profile.timing_library}",
            f"Include Files: {', '.join(profile.include_files)}",
            f"MPI Support: {'Yes' if profile.mpi_support else 'No'}",
            f"Initialization Calls: {len(profile.init_calls)}",
            f"Finalization Calls: {len(profile.finalize_calls)}",
        ]

        if profile.preprocessor_defines:
            info.append(f"Preprocessor Defines: {', '.join(profile.preprocessor_defines)}")
        if profile.link_libraries:
            info.append(f"Link Libraries: {', '.join(profile.link_libraries)}")
        if profile.compiler_flags:
            info.append(f"Compiler Flags: {' '.join(profile.compiler_flags)}")

        return "\n".join(info)


# Global platform registry
platform_registry = PlatformRegistry()